#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>

#define WIFI_SSID "แก้ไข"  // Replace with your Wi-Fi SSID
#define WIFI_PASSWORD "แก้ไข"  // Replace with your Wi-Fi password
#define LINE_TOKEN_PIR "แก้ไข"  // Replace with your LINE Notify token
#define PirPin D6

String message1 = "แก้ไข";  // Message to send via LINE Notify
bool beep_state = false;
uint32_t ts, ts1, ts2;

void setup() {
  Serial.begin(115200);
  pinMode(PirPin, INPUT);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);
  
  Serial.println("Connecting to Wi-Fi...");
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  
  Serial.println();
  Serial.print("Connected: ");
  Serial.println(WiFi.localIP());
  
  delay(10000);
  Serial.println("PIR Ready!!");
  ts = ts1 = ts2 = millis();
}

void loop() {
  ts = millis();
  
  // Check Wi-Fi connection status
  if (WiFi.status() == WL_CONNECTED) {
    digitalWrite(LED_BUILTIN, LOW);
  } else {
    digitalWrite(LED_BUILTIN, HIGH);
  }

  // Reset beep_state after 5 seconds
  if ((ts - ts1 >= 5000) && (beep_state == true)) {
    beep_state = false;
  }

  // If PIR sensor is triggered
  if ((digitalRead(PirPin) == HIGH) && (beep_state == false) && (WiFi.status() == WL_CONNECTED)) {
    while (digitalRead(PirPin) == HIGH) delay(100);  // Wait until the sensor is low again
    Serial.println("Motion Detected!");
    Line_Notify1(message1);
    beep_state = true;
  }

  delay(10);
}

void Line_Notify1(String message) {
  WiFiClientSecure client;
  client.setInsecure();  // Use this method for insecure connections

  // Connect to LINE Notify API
  if (!client.connect("notify-api.line.me", 443)) {
    Serial.println("Connection failed!");
    delay(2000);
    return;
  }

  // Prepare the HTTP POST request
  String req = "";
  req += "POST /api/notify HTTP/1.1\r\n";
  req += "Host: notify-api.line.me\r\n";
  req += "Authorization: Bearer " + String(LINE_TOKEN_PIR) + "\r\n";
  req += "Cache-Control: no-cache\r\n";
  req += "User-Agent: ESP8266\r\n";
  req += "Content-Type: application/x-www-form-urlencoded\r\n";
  req += "Content-Length: " + String(String("message=" + message).length()) + "\r\n";
  req += "\r\n";
  req += "message=" + message;

  // Send the request
  client.print(req);

  // Wait for server response
  while (client.connected()) {
    String line = client.readStringUntil('\n');
    if (line == "\r") {
      break;
    }
  }

  // Optionally, handle response here
  Serial.println("Notification sent!");
}
